/*
*****************************************************************
Title: How Does Removing the Tax Benefits of Debt Affect Firms? Evidence from the 2017 US Tax Reform
Authors: 
Discription: 

The views expressed in this paper are solely those of the authors. They do not necessarily reflect the views of the Federal Reserve Board or the Federal Reserve System.
*****************************************************************
*/

clear all
clear matrix
clear mata
set more off
set memory 1500m
set matsize 10000

*** In the first step, we use raw data from Y-14Q dataset to generate a cleaned sample of firm-year observations in panel format.

	* NOTE: Directory names and raw variable names are masked to comply with Federal Reserve's confidentiality requirements.
	* We convert all variables with dollar values into real values using CPI deflator data ($ 2015 = 100)
	* We winsorize all raw varaiables at cuts(1 99)
	/* As an example:
	replace totalliabilities = (100*totalliabilities)/cpi
	winsor2 totalliabilities, replace cuts(1 99)
	*/

	* A cleaned panel dataset is saved with the name "data_cleaned"
		
	
*****************************************************************	
	use "data_cleaned",clear

	/* 
	Dropping the following industries:
	 agriculture NAICS 11
	 utilities NACIS 22, NAICS 5621, 5622, 5629
	 public admin NAICS 92
	 Finance and Real Estate naics 52-53
	 motor vehicle dealers, including:
		New car dealers 441110
		Used car dealers 441120
		Boat delaers 441222
		Recreational vehicles delaers 441210
		Motorcycle dealers 441228
		Automotive delaers, nec 441228
	*/

	drop if naics2==11	
	drop if naics2==22 | inlist(naics4, "5621", "5622", "5629")
	drop if naics2==92
	drop if inlist(naics2, 52, 53)
	drop if inlist(naics, 441110, 441120, 441222, 441210, 441228, 441228 )
	
	gen fyear = year
	xtset newid fyear
	
	gen capital = nonfin_assets
	replace sale = sales if missing(sale)	// sale is a compustat variable. sales is a y14 variable.
	replace size = log(1+ totalassetscurrent)
	gen prof = opincome/ totalassetscurrent
	gen debt = totalliabilities
	
	gen lev = debt / nonfin_assets
	gen comstock_c = equity_cs / nonfin_assets
	gen totfinratio = (debt + equity_cs) / nonfin_assets // total external financing
	gen inv = capx/l.nonfin_assets	// investment rate
	gen gp = opincome // Gross profit = sales minus cogs = opincome
	/* Non debt tax shield = (depreciation+amortization+ investment tax credit)/gross profit(if gross profit>0)
	total liabilities – current liabilities – long-term debt = other non-current liabilities (including deferred taxes, investment tax credit, and minority interest) 
	we use depreciation/amortization instead of non debt tax shield*/
	gen ndshield_gp = depreciation/(gp*(gp>0))
	gen int_opincome = interest/opincome

	* There is little variation and missing values in original data on tangible assets. So for each firm we use average tangibility (ppent/total assets) based on average NAICS4-YEAR values provided by Compustat instead (2016-2019).
	merge m:1 naics4 fyear using "data_tang_naics4"
		drop if _merge==2
		drop _merge
		
	gen tang = tang_naics4
	replace tang = tangibility if missing(tang) // tangibility: For compustat it is the original value. For y14 calculatd consistently.	

	xtset
	foreach i in size q_ind prof tang tang1 {
		gen L`i'=L.`i'
	}
	
	drop if capital<1
	drop if equity<=0
	
	* Saving a version of the data for placebo tests:
	save "data_RDD_placebo", replace
	
	*****************************************************************	

	** Modifying the clean sample for the baseline RDD tests:
	
	xtset
	
	* Replacing the average sales data for firms without three consecutive years of sales data:
	gen avgsale1 = L.sale
	gen avgsale2 = (L.sale+L2.sale)/2
	gen avgsale3 = (L.sale+L2.sale+L3.sale)/3
	
	gen avgsale = avgsale3
	replace avgsale = avgsale2 if avgsale==.
	replace avgsale = avgsale1 if avgsale==.
	
	* Sample years: 2016-2019:
	drop if fyear<2016
	gen after=0
	replace after=1 if fyear>=2018
	
	*********************************
	
	gen idit=0	//Data does not report interest income. This biases our results downward.
	
	* Defining high-interest based on all years (if interest expense > (interest income + 0.3 X EBITDA)). 
	gen hiint=0 if interest~=.
	replace hiint=1 if (interest>(idit+0.3*opincome) & interest~=.) //opincome is the corrected version of ebitda
	keep if hiint==1

	* Defining treated based on all years
	gen treated=0 if avgsale~=.
	replace treated=1 if (avgsale>25 & avgsale~=.)
		
	* During 2018-2019 ("after") we want to see if a firm is treated in one year and not in other ("switching")
	gen posttreat= 1 if treated & after
	replace posttreat = 0 if missing(posttreat)
	egen posttreatsum = sum(posttreat), by(newid)
	
	* it is possible that switching firms are firms that are only present in one year and they are not really switching
	egen nafter = sum(after), by(newid)
	tab posttreatsum nafter, missing
	gen switching = (posttreatsum ==1 & nafter==2)	

	
	* Up to this point, the sample construction is the same for 1) the main RDD tests and 2) DID tests

	save tax_cleanedsample_stage1, replace
	
	*********************************

	*** Information for summary stat table (number of observations in the panel before collapsing by firm level):
	
	global sumstat_firm "capital avgsale lev comstock_c inv q_ind prof tang debt interest opincome int_opincome" 
	
	bysort newid: egen drop_dummy = mean(after) //drop_dummy=0 means all obs are from before, drop_dummy=1 means all obs are from after, 0<drop_dummy<1 means the firm has obs both before and after
	drop if inlist(drop_dummy, 0, 1)

	bysort newid after: egen avgsale_mean = mean(avgsale)
	replace avgsale_mean=. if after==0
	by newid: egen avgsale_mean2 = mean(avgsale_mean)
	keep if avgsale_mean2>=25-(15) & avgsale_mean2<=25+(15)

	keep if ~switching
	bysort newid: egen treated_mean = mean(treated)
	keep if treated_mean==0 | treated_mean==1
	
	gen cash_a = cashmarketable / totalassetscurrent
	tab public, sum(cash_a)
	tab public if after==0, sum(cash_a)

	
	* Sum Stat Firm Charactersitcis (Table 1) focus on number of panel obs
	
	eststo: estpost tabstat $sumstat_firm if inlist(treated, 0, 1), statistics(count mean sd) columns(statistics) 

	eststo: estpost tabstat $sumstat_firm if treated==0 & after==0, statistics(count mean sd) columns(statistics) 

	eststo: estpost tabstat $sumstat_firm if treated==1 & after==0, statistics(count mean sd) columns(statistics) 
	
	*********************************
	
	*** Constructing the main RDD sample:
	
	use tax_cleanedsample_stage1, clear
	
	global covariates size q_ind prof tang
	global basedepvar lev inv comstock_c totfinratio
	global othervars sale avgsale treated switching
	global othervars2 totalassetscurrent capital Lsize Lq_ind Lprof Ltang idit opincome gp ndshield_gp interest int_opincome
	
	* Collapsing the panel data to firm level before and after:
	collapse (last) naics naics2 naics4 public (mean)  $basedepvar $depvar2 $covariates $othervars $othervars2, by(newid after)

	* Keep firms that exist in the data both before and after the shock:
	by newid: gen cnt=_N
	keep if cnt==2

	sort newid after
	ds $covariates
	foreach var in $basedepvar `r(varlist)' {
		sort newid after
		by newid: gen D`var'=`var'[_N]-`var'[1]
	}
	
	foreach var in $basedepvar $covariates $othervars $othervars2 {
		sort newid after
		by newid: gen `var'_pre=`var'[1]
	}

	by newid: egen grandavgsale=mean(avgsale)
	forvalues j=1/4 {
		gen salediffP`j'=(grandavgsale - 25)^`j'
	}

	by newid: keep if _n==_N
	
	winsor2 D* $basedepvar $depvar2 $covariates $othervars $othervars2 , replace cuts(3 97)
	
	keep if ~switching
	keep if treated==0 | treated==1

	global RHSP1 c.treated##c.salediffP1
	global RHSP2 c.treated##c.salediffP1 c.treated##c.salediffP2
	global RHSP3 c.treated##c.salediffP1 c.treated##c.salediffP2 c.treated##c.salediffP3

	global keeplist1 treated salediffP1 c.treated#c.salediffP1 Dsize Dq_ind Dprof Dtang Dtang1 _cons
	global keeplist2 treated salediffP1 c.treated#c.salediffP1 salediffP2 c.treated#c.salediffP2 Dsize Dq_ind Dprof Dtang  _cons
	global keeplist3 treated salediffP1 c.treated#c.salediffP1 salediffP2 c.treated#c.salediffP2 salediffP3 c.treated#c.salediffP3 Dsize Dq_ind Dprof Dtang  _cons
	
	destring naics4, replace
	
	***************************************************************************************************
	***************************************************************************************************
	* Results:
	***************************************************************************************************
	***************************************************************************************************

	*** Summary stat table for the baseline sample:
	label var capital "Capital (\$ mil.)"
	label var grandavgsale "3-year avg. sales (\$ mil.)"
	label var debt "Debt (\$ mil.)"
	label var equity_cs "Common Stock (\$ mil.)"
	label var capx "Investment (\$ mil.)"
	label var lev "Debt ratio"
	label var comstock_c "Common stock ratio"
	label var inv "Investment rate"
	label var q_ind "Market-to-book"
	label var prof "Profitability"
	label var tang "Tangibility"
	
	label var Dlev "\Delta Debt ratio"
	label var Dcomstock_c "\Delta Common stock ratio"
	label var Dtotfinratio "\Delta Total financing ratio"
	label var Dinv "\Delta Investment rate"
	label var Dq_ind "\Delta Market-to-book"
	label var Dprof "\Delta Profitability"
	label var Dtang "\Delta Tangibility"
	

	global sumstat_firm "capital grandavgsale lev comstock_c inv q_ind prof tang debt interest opincome int_opincome" 
	global sumstat_firm_pre "capital_pre grandavgsale lev_pre comstock_c_pre inv_pre q_ind_pre prof_pre tang_pre debt_pre interest_pre opincome_pre int_opincome_pre" 
	global sumstat_outcome "Dlev Dcomstock_c Dtotfinratio Dinv Dq_ind Dprof Dtang"
	
	************************************************************************************************************************************	
	* Sum Stat table (Table 1)	
	************************************
	preserve
		local win=10
		keep if avgsale>=25-`win' & avgsale<=25+`win'
		
		hist prof, xlabel( , grid glpattern(dot) ) ylabel( , grid glpattern(dot) )  scheme(s1mono)
		graph export "Figures/fig_profhist.png", as(png) replace
		sum prof,d
	restore

	preserve
		local win=10
		keep if avgsale>=25-`win' & avgsale<=25+`win'
		tab public
	restore
	
	* Sum Stat Firm Charactersitcis (Table 1)
	eststo clear  
	eststo: estpost tabstat $sumstat_firm if inlist(treated, 0, 1), statistics(count mean sd) columns(statistics) 
	esttab using "LaTex/table_SumStat_firm_all.tex", cell((count(label(\multicolumn{1}{c}{}) fmt(%9.0fc)) mean(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) sd(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) )) ///
		noobs nostar unstack nonote nonumber label fragment booktabs replace

	eststo clear  
	eststo: estpost tabstat $sumstat_firm_pre if treated==0, statistics(count mean sd) columns(statistics) 
	esttab using "LaTex/table_SumStat_firm_control_pre.tex", cell((count(label(\multicolumn{1}{c}{}) fmt(%9.0fc)) mean(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) sd(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) )) ///
		noobs nostar unstack nonote nonumber label fragment booktabs replace

	eststo clear  
	eststo: estpost tabstat $sumstat_firm_pre if treated==1, statistics(count mean sd) columns(statistics) 
	esttab using "LaTex/table_SumStat_firm_treated_pre.tex", cell((count(label(\multicolumn{1}{c}{}) fmt(%9.0fc)) mean(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) sd(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) )) ///
		noobs nostar unstack nonote nonumber label fragment booktabs replace
		
		
	* Sum Stat Outcome variables (Table 1)
	eststo clear  
	eststo: estpost tabstat $sumstat_outcome if inlist(treated, 0, 1), statistics(count mean sd) columns(statistics) 
	esttab using "LaTex/table_SumStat_outcome_all.tex", cell((count(label(\multicolumn{1}{c}{}) fmt(%9.0fc)) mean(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) sd(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) )) ///
		noobs nostar unstack nonote nonumber label fragment booktabs replace

	eststo clear  
	eststo: estpost tabstat $sumstat_outcome if treated==0, statistics(count mean sd) columns(statistics) 
	esttab using "LaTex/table_SumStat_outcome_control.tex", cell((count(label(\multicolumn{1}{c}{}) fmt(%9.0fc)) mean(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) sd(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) )) ///
		noobs nostar unstack nonote nonumber label fragment booktabs replace

	eststo clear  
	eststo: estpost tabstat $sumstat_outcome if treated==1, statistics(count mean sd) columns(statistics) 
	esttab using "LaTex/table_SumStat_outcome_treated.tex", cell((count(label(\multicolumn{1}{c}{}) fmt(%9.0fc)) mean(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) sd(label(\multicolumn{1}{c}{}) fmt(%9.3fc)) )) ///
		noobs nostar unstack nonote nonumber label fragment booktabs replace

		
	************************************************************************************************************************************
	* Rest of Tables
	************************************************************************************************************************************
	*** Testing predetermined firm characteristics (Table 2):

	* using avgsale:
	preserve
	
	keep if inlist(treated, 0, 1)
	foreach var in q_ind_pre prof_pre tang_pre lev_pre comstock_c_pre inv_pre {
			
			rd `var' avgsale, z0(25) cluster(naics4)

	}
		
	restore
	
	************************************************************************************************************************************	
	*** Testing firm outcomes with ratio variables (Tables 3 and 5):
	
	** With optimal window:	
	eststo clear
	foreach var in Dlev  Dtotfinratio Dcomstock_c {
		rdbwselect `var' avgsale, c(25) p(2) vce(cluster naics2) all kernel(uniform) covs(Dsize Dq_ind Dprof Dtang)
		qui reg `var' $RHSP2 Dsize Dq_ind Dprof Dtang i.naics4 if avgsale>=25-e(h_cerrd) & avgsale<=25+e(h_cerrd), vce(cluster naics2)
			est store `var'_p2c_opt
	}
	foreach var in Dinv {
		rdbwselect `var' avgsale, c(25) p(2) vce(cluster naics2) all kernel(uniform) covs(Dq_ind Dprof)
		qui reg `var' $RHSP2 Dq_ind Dprof i.naics4 if avgsale>=25-e(h_cerrd) & avgsale<=25+e(h_cerrd), vce(cluster naics2)
			est store `var'_p2c_opt
	}
	foreach var in Dq_ind Dprof Dtang {
		rdbwselect `var' avgsale, c(25) p(2) vce(cluster naics2) all kernel(uniform)
		qui reg `var' $RHSP2 i.naics4 if avgsale>=25-e(h_cerrd) & avgsale<=25+e(h_cerrd), vce(cluster naics2)
		est store `var'_p2nc_opt
	} 
	
	*****************************************************
	** Exporting Latex table:
	
	* Firm financing and investment (Table 3):
	esttab 	Dlev_p2c_opt Dcomstock_c_p2c_opt Dtotfinratio_p2c_opt Dinv_p2c_opt ///
			using "LaTex/table_ratios_fininv_p2_optwin.tex", ///
			replace se ar2 nogaps  b(%9.3f) star(* 0.1 ** 0.05 *** 0.01) ///
			keep($keeplist2) order($keeplist2)
	
	* Firm characteristics (Table 5):
	esttab 	Dq_ind_p2nc_opt Dprof_p2nc_opt Dtang_p2nc_opt ///
			using "LaTex/table_ratios_firmchars.tex", ///
			replace se ar2 nogaps  b(%9.3f) star(* 0.1 ** 0.05 *** 0.01) ///
			keep($keeplist2) order($keeplist2)

	************************************************************************************************************************************
	
	**** Regressions with interactions and sorts:
	
	** Sorts on profits (Table 4, columns 1-2):
	preserve
	
	local win 10
	keep if avgsale>=25-`win' & avgsale<=25+`win'
	
	foreach pct in 50 {
		egen gp_pre_winp`pct' = pctile(gp_pre), p(`pct')
		gen higp_pre_winp`pct' = 0 if ~missing(gp_pre)
		replace higp_pre_winp`pct' = 1 if ~missing(gp_pre) & gp_pre > gp_pre_winp`pct'
	}
	gen hiprof_gp_pre = higp_pre_winp50
	
	foreach var in Dlev Dcomstock_c {
		qui reg `var' c.treated##c.hiprof_gp_pre $RHSP2 Dsize Dq_ind Dprof Dtang i.naics4, vce(cluster naics2)
			est store `var'_p2c_higp
	}
	restore
	
	** Sorts on non-debt tax sheilds (Table 4, columns 3-4):
	preserve
	
	local win 10
	keep if avgsale>=25-`win' & avgsale<=25+`win'
	
	local ndvar ndshield_gp_pre
	foreach pct in 50 {
		egen `ndvar'_winp`pct' = pctile(`ndvar'), p(`pct')
		gen lo`ndvar'_winp`pct' = 0 if ~missing(gp_pre)
		replace lo`ndvar'_winp`pct' = 1 if ~missing(`ndvar') & `ndvar' < `ndvar'_winp`pct'
	}
	gen londshield_gp = lo`ndvar'_winp50
	
	
	foreach var in Dlev Dcomstock_c {
		qui reg `var' c.treated##c.londshield_gp $RHSP2 Dsize Dq_ind Dprof Dtang i.naics4, vce(cluster naics2)
			est store `var'_p2c_lond
	}

	restore

	*****************************************************
	* Exporting Latex table:
	
	* Table for hiprof and londshield interactions (Table 4):
	esttab 	Dlev_p2c_higp Dcomstock_c_p2c_higp Dlev_p2c_lond Dcomstock_c_p2c_lond  ///
			using "LaTex/table_sorts_gp_ndshield.tex", ///
			replace se ar2 nogaps  b(%9.3f) star(* 0.1 ** 0.05 *** 0.01) ///
			keep(c.treated#c.hiprof_gp_pre hiprof_gp_pre c.treated#c.londshield_gp londshield_gp $keeplist2) ///
			order(c.treated#c.hiprof_gp_pre hiprof_gp_pre c.treated#c.londshield_gp londshield_gp $keeplist2)
	
	*****************************************************
	
	*** Sorting on cash constraints (Table 6)
	
	preserve
	
	global cashcontrols c.treated##c.locash $RHSP2

	local win 10
	keep if avgsale>=25-`win' & avgsale<=25+`win'
		
	local revar re_c
	foreach pct in 50 {
		egen `revar'_winp`pct' = pctile(`revar'), p(`pct')
		gen lo`revar'_winp`pct' = 0 if ~missing(`revar')
		replace lo`revar'_winp`pct' = 1 if ~missing(`revar') & `revar' < `revar'_winp`pct'
	}
	gen locash = lo`revar'_winp50
	
	foreach var in Dlev Dtotfinratio Dcomstock_c {
		qui reg `var' $cashcontrols Dsize Dq_ind Dprof Dtang i.naics4, vce(cluster naics2)
			est store `var'_p2c_locash
	}
	foreach var in Dinv Dinv2 DLnonfin_assets {
		qui reg `var' $cashcontrols Dq_ind Dprof i.naics4, vce(cluster naics2)
			est store `var'_p2c_locash
	}	
	
	restore

	*****************************************************
	* Exporting Latex table:
	
	* Table for sorts based on cash constraints (Table 6)
	
	esttab 	Dlev_p2c_locash Dcomstock_c_p2c_locash Dtotfinratio_p2c_locash  Dinv2_p2c_locash  ///
			using "LaTex/table_sorts_cashconst.tex", ///
			replace se ar2 nogaps  b(%9.3f) star(* 0.1 ** 0.05 *** 0.01) ///
			keep(c.treated#c.locash locash $keeplist2) order(c.treated#c.locash locash $keeplist2)

	*****************************************************
	
	*** Sorting on positive and negative profits (Table 7):

	gen posprof = 1 if ~missing(gp_pre) & gp_pre>0
	replace posprof = 0 if ~missing(gp_pre) & gp_pre<=0
	
	forvalues i = 0/1 {
		preserve
		rdbwselect Dlev avgsale if posprof==`i', c(25) p(2) vce(cluster naics2) all kernel(uniform) covs(Dsize Dq_ind Dprof Dtang)
		keep if avgsale>=25-e(h_cerrd) & avgsale<=25+e(h_cerrd)

		qui reg Dlev $RHSP2 Dsize Dq_ind Dprof Dtang i.naics4 if posprof==`i', vce(cluster naics2)
			est store Dlev1_gp_`i'
		restore
		
		preserve
		rdbwselect Dcomstock_c avgsale if posprof==`i', c(25) p(2) vce(cluster naics2) all kernel(uniform) covs(Dsize Dq_ind Dprof Dtang)
		keep if avgsale>=25-e(h_cerrd) & avgsale<=25+e(h_cerrd)

		qui reg Dcomstock_c $RHSP2 Dsize Dq_ind Dprof Dtang i.naics4 if posprof==`i', vce(cluster naics2)
			est store Dcomstock_c_gp_`i'
		restore
		
		preserve
		rdbwselect Dinv avgsale if posprof==`i', c(25) p(2) vce(cluster naics2) all kernel(uniform) covs(Dq_ind Dprof)
		keep if avgsale>=25-e(h_cerrd) & avgsale<=25+e(h_cerrd)

		qui reg Dinv $RHSP2 Dq_ind Dprof i.naics4 if posprof==`i', vce(cluster naics2)
			est store Dinv_gp_`i'
		restore
	}

	*****************************************************
	* Exporting Latex table:
	
	* Table for positive and negative profits (Table 7)
	
	esttab 	Dlev1_gp_0 Dcomstock_c_gp_0 Dinv_gp_0 Dlev1_gp_1 Dcomstock_c_gp_1 Dinv_gp_1 ///
			using "LaTex/table_sorts_posprof.tex", ///
			replace se ar2 nogaps  b(%9.3f) star(* 0.1 ** 0.05 *** 0.01) ///
			keep($keeplist2) order($keeplist2)
			
			
	************************************************************************************************************************************
	
	*** Interactions with public (Table B.2 in Appendix B)
	
	global RHSP2inter c.public##(c.treated##c.salediffP1 c.treated##c.salediffP2)
	global keeplist2inter treated c.public#c.treated public Dsize Dq_ind Dprof Dtang  _cons

	preserve
	
	local win 10
	keep if avgsale>=25-`win' & avgsale<=25+`win'
		
	foreach var in Dlev1 Dcomstock_c Dtotfinratio {
		qui reg `var' $RHSP2inter Dsize Dq_ind Dprof Dtang i.naics4 , vce(cluster naics2)
			est store `var'_p2c_w`win'
	}
	foreach var in Dinv  {
		qui reg `var' $RHSP2inter Dq_ind Dprof i.naics4 , vce(cluster naics2)
			est store `var'_p2c_w`win'
	}	
	restore
	
	*****************************************************
	* Exporting Latex table:
	
	* Firm financing and investments with interactions with public indicator (Table B.2):
	esttab Dlev1_p2c_w`win' Dcomstock_c_p2c_w`win' Dtotfinratio_p2c_w`win' Dinv_p2c_w`win' ///
		using "LaTex/table_ratios_publicprivate.tex", ///
		ar2 nogaps b(%9.3f) star(* 0.1 ** 0.05 *** 0.01) ///
		keep($keeplist2inter) order($keeplist2inter)	
	
	************************************************************************************************************************************	

	*** Difference in differences (Appendix D, Table D.4):
		
	use tax_cleanedsample_stage1, clear
	
	keep if ~switching
	global covariates size q_ind prof tang
	global basedepvar lev inv comstock_c totfinratio

	winsor2 $covariates $basedepvar , replace cuts(1 99)
	
	xtset newid fyear
	
	foreach i in $basedepvar  {
		bysort naics2 fyear: egen `i'_ind=median(`i')
	}

	global debtcontrols Lsize Lq_ind Lprof Ltang
	global invcontrols  Lq_ind Lprof 

	preserve
	
	local win 10
	keep if avgsale>=25-`win' & avgsale<=25+`win'
	
	xtset newid fyear
	
	foreach i in lev comstock_c totfinratio {
		qui reghdfe `i' c.treated#c.after $debtcontrols `i'_ind , absorb(newid fyear) vce(cluster newid)
			est store `i'
	}
	qui reghdfe inv c.treated#c.after $invcontrols , absorb(newid fyear) vce(cluster newid)
		est store inv
		
	global keeplist c.treated#c.after $debtcontrols *_ind
	
	restore

	* Dynamic DID:

	preserve
	local win 10
	keep if avgsale>=25-`win' & avgsale<=25+`win'
	
	xtset newid fyear
	
	local indepvar c.treated#(2017.fyear 2018.fyear 2019.fyear)
	
	foreach i in lev comstock_c totfinratio {
		qui reghdfe `i' `indepvar' $debtcontrols `i'_ind , absorb(newid fyear) vce(cluster newid)
			est store `i'_dyn
	}
	qui reghdfe inv `indepvar' $debtcontrols inv_ind , absorb(newid fyear) vce(cluster newid)
		est store inv_dyn

	restore

	*****************************************************
	* Exporting Latex table:
	
	* Diff-in-Diff table (Table D.4 in Appendix D)
	
	esttab lev comstock_c totfinratio inv lev_dyn comstock_c_dyn totfinratio_dyn inv_dyn ///
		using "LaTex/table_DID.tex", ///
		replace se ar2 b(%9.3f) star(* 0.1 ** 0.05 *** 0.01)
	
************************************************************************************************************************************	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
